package ustc.xiaoyang.karl.linkedlist;

/**
 * 707.设计链表
 */
public class DesignLinkedList707 {
    private ListNode dummy;
    private int size;

    public DesignLinkedList707() {
        dummy = new ListNode(0,null);
        size = 0;
    }

    public int get(int index) {
        if(index<0 || index >= size) return -1;
        ListNode cur = dummy;
        for (int i = 0; i < index+1; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        dummy.next = new ListNode(val, dummy.next);
        size++;
    }

    public void addAtTail(int val) {
        ListNode cur = dummy;
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = new ListNode(val,null);
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size) return;
        ListNode cur = dummy;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        cur.next = new ListNode(val,cur.next);
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index<0 || index > size-1) return;
        ListNode cur = dummy;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        size--;
    }


}
